//
//  ActivityPalceController.m
//  i5db
//
//  Created by iMuse on 15-5-22.
//  Copyright (c) 2015年 mySelf. All rights reserved.
//

#import "ActivityPalceController.h"
#import "PullTableView.h"
#import "AppCenter.h"
#import "SearRsultModel.h"
#import "NotificationNavView.h"
#import "MJRefresh.h"
#import "HUD.h"

#import <BaiduMapAPI/BMapKit.h>


#define TengXunKey @"A66BZ-K5O3S-22OOT-6HYDR-N47E5-XCBNH"
#define cellHeight 40
@interface ActivityPalceController ()<UITableViewDataSource,UITableViewDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate>
{
    UITableView           * pullTableView;
    NSMutableArray          * dataArray;
    UIView                  * searchView;
    UIView                  * searchBackView;
    NSInteger                 page;
    NSInteger                 status;
    
    UITextField             * textField;
    NSInteger                 count;
    
    UIView                  * loadingView;
    
    NSLayoutConstraint      * loadingHeight;
    
    BMKMapView              *_mapView;
    BMKLocationService      * _locService;
    
    UILabel                 * loadingLabel;
    
    NSInteger               headerHeight;

  
}

@property(nonatomic,assign) double   latitude;
@property(nonatomic,assign) double   longitude;
@property(nonatomic,assign) NSInteger type;

@end

@implementation ActivityPalceController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
      self.title = @"活动地点";
        dataArray = [[NSMutableArray alloc] init];
        page = 1;
        status  = 0;
        self.type    = 0; //0附近的位置 1 用户自己搜索
       
    }
    return self;
}

-(void)updateViewConstraints
{
    [super updateViewConstraints];
  
    
    [searchView autoPinToTopLayoutGuideOfViewController:self withInset:0];
    [searchView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
    [searchView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
    [searchView autoSetDimension:ALDimensionHeight toSize:cellHeight];
    
    [searchBackView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:4];
    [searchBackView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:5];
    [searchBackView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:5];
    [searchBackView autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:4];
    
    [loadingView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:searchView withOffset:0];
    [loadingView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
    [loadingView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
    
    
     [pullTableView autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:loadingView withOffset:-64];
     [pullTableView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
     [pullTableView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
     [pullTableView autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0];
    
    
}
-(void) initNavigationBar
{
    [super initNavigationBar];
}
-(void)back:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setNeedsUpdateConstraints];
    [self initNavigationBar];
    [self initView];
    [self startLocation];
    

  
   
}

-(void)startLocation
{
   
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];

    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
  
}


-(void)initView
{
    
    pullTableView  = [UITableView newAutoLayoutView];
    
    pullTableView.delegate = self;
    pullTableView.dataSource = self;
  
    [self.view addSubview:pullTableView];
   
    __weak typeof(self) weakSelf = self;
    
    [pullTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf loadMoreData];
    }];

    
    pullTableView.tableFooterView = [[UIView alloc] init];
    
    searchView = [UIView newAutoLayoutView];
    searchView.backgroundColor = [AppCenter color:@"203,203,203,1"];
    [self.view addSubview:searchView];
    
    searchBackView = [UIView newAutoLayoutView];
    searchBackView.backgroundColor = [UIColor whiteColor];
    searchBackView.layer.cornerRadius = 4;
    [searchView addSubview:searchBackView];
    
    UIImageView * imageView = [UIImageView newAutoLayoutView];
    imageView.image = [UIImage imageNamed:@"qq_active_search_finder_grey.png"];
    [searchBackView addSubview:imageView];
    [imageView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:5];
    [imageView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:5];
    [imageView autoSetDimensionsToSize:CGSizeMake(20, 20)];
    
    textField = [UITextField newAutoLayoutView];
    textField.placeholder = @"搜索地址";
    textField.textColor = [AppCenter color:@"143,143,143,1"];
    textField.font = [UIFont systemFontOfSize:12];
    [searchBackView addSubview:textField];
    [textField autoPinEdge:ALEdgeLeft toEdge:ALEdgeRight ofView:imageView withOffset:2];
    [textField autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
    [textField autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0];
    [textField autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:10];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textDidChanged:) name:UITextFieldTextDidChangeNotification object:textField];
    
    loadingView = [UIView newAutoLayoutView];
    loadingView.hidden = YES;
    loadingView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:loadingView];
    loadingLabel = [UILabel newAutoLayoutView];
    loadingLabel.backgroundColor = [AppCenter color:@"244,244,244"];
    loadingLabel.text = @"正在加载......";
    loadingLabel.textAlignment = NSTextAlignmentCenter;
    loadingLabel.textColor = [AppCenter color:@"143,143,143"];
    loadingLabel.font = [UIFont systemFontOfSize:10];
    [loadingView addSubview:loadingLabel];
    [loadingLabel autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
   
    loadingHeight = [loadingView autoSetDimension:ALDimensionHeight toSize:20];
   
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* identifier = @"i5dbIndefter";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UILabel * titleLabel    = nil;
    UILabel * subTitleLabel = nil;
    UILabel * line = nil;
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:identifier] ;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        line = [UILabel newAutoLayoutView];
        line.backgroundColor = [AppCenter color:@"225,225,225"];
        [cell.contentView addSubview:line];
        [line autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
        [line autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
        [line autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0];
        [line autoSetDimension:ALDimensionHeight toSize:0.5];
        
        titleLabel = [UILabel newAutoLayoutView];
        titleLabel.font = [UIFont boldSystemFontOfSize:13];
        titleLabel.tag = 1;
        [cell.contentView addSubview:titleLabel];
        [titleLabel autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:5];
        [titleLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:10];
        
        subTitleLabel = [UILabel newAutoLayoutView];
        subTitleLabel.font = [UIFont systemFontOfSize:10];
        subTitleLabel.textColor = [AppCenter color:@"143,143,143,1"];
        subTitleLabel.tag = 2;
        [cell.contentView addSubview:subTitleLabel];
        [subTitleLabel autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:titleLabel withOffset:5];
        [subTitleLabel autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:10];
        
    }else
    {
        titleLabel = (UILabel*)[cell.contentView viewWithTag:1];
        subTitleLabel = (UILabel*)[cell.contentView viewWithTag:2];
    }
    SearRsultModel * model = [dataArray objectAtIndex:[indexPath row]];
    titleLabel.text = model.title;
    subTitleLabel.text = model.address;
    
    return cell;
}

-(void)textDidChanged:(NSNotification*) notification
{
    UITextField * field = (UITextField*) notification.object;
    UITextRange * range =  [field markedTextRange];
    if (range==nil || range.empty)
    {
   
        NSString * string = [AppCenter string:field.text];
       
        if ([string isEqualToString:@""] || !string) {
            return;
        }
        page = 1;
        
        [self showLoadingView];
        
        if (dataArray.count>0)
        {
            [dataArray removeAllObjects];
        }
        self.type = 1;
        [self getSeverData:string];
    }
}

-(void) showLoadingView
{
    loadingView.hidden = NO;
    loadingHeight.constant = 20;
}
-(void) hiddenLoadingView
{
    loadingHeight.constant = 0;
    loadingView.hidden = YES;
}

-(void)getNearServiceData
{
    
    NSString * pageString = [NSString stringWithFormat:@"%d",page];
    NSString * boundary = [NSString stringWithFormat:@"nearby(%f,%f,1000)",self.latitude,self.longitude];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    NSDictionary *parameters = @{ @"boundary":boundary,@"keyword":@"休闲娱乐",@"page_size":@"10",@"page_index":pageString,@"orderby":@"_distance",@"key":TengXunKey};
   
    [manager GET:[AppCenter TengXuanWebService] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSError * error ;
        count = [responseObject[@"count"] integerValue];
   
        NSInteger webStatus = [responseObject[@"status"] integerValue];
        if (webStatus!=0)
        {
            NSLog(@"%@",responseObject[@"message"]);
            [NotificationNavView showMessage:@"webService出错"];
         
            
            return ;
        }
        
        [self clerStatus];
        NSArray * array  = [SearRsultModel arrayOfModelsFromDictionaries:responseObject[@"data"] error:&error];
        if (error)
        {
            [NotificationNavView showMessage:@"检索出错"];
           
        }else
        {
            if (array)
            {
                if (array.count>0)
                {
                    
                    page++;
                    [dataArray addObjectsFromArray:array];
                }
                [pullTableView reloadData];
                
               
                [self hiddenLoadingView];
            }
            
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [NotificationNavView showMessage:@"网络异常"];
      
    }];
   
}



-(void) getSeverData:(NSString*) text
{

    NSString * pageString = [NSString stringWithFormat:@"%d",page];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
        NSDictionary *parameters = @{ @"boundary":@"region(北京,0)", @"keyword":text,@"page_size":@"10",@"page_index":pageString,@"orderby":@"_distance",@"key":TengXunKey};
    
    [manager GET:[AppCenter TengXuanWebService] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError * error ;
      
        count = [responseObject[@"count"] integerValue];
        NSInteger webStatus = [responseObject[@"status"] integerValue];
        if (webStatus!=0)
        {
            [NotificationNavView showMessage:@"webService出错"];
            
            return ;
        }
      
        [self clerStatus];
        NSArray * array  = [SearRsultModel arrayOfModelsFromDictionaries:responseObject[@"data"] error:&error];
        
        if (error)
        {
            [NotificationNavView showMessage:@"检索出错"];
        }else
        {
            if (array)
            {
                
                if (array.count>0)
                {
                    
                    page++;
                    [dataArray addObjectsFromArray:array];
                }
                [pullTableView reloadData];
               
                [self hiddenLoadingView];
            }
            
        }
    
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [NotificationNavView showMessage:@"网络异常"];
    }];
}

-(void)clerStatus
{
   
    [pullTableView.footer endRefreshing];
   
     status = 0;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return dataArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return cellHeight;
}

-(void)loadMoreData
{
    if (status!=0)
    {
        [pullTableView.footer endRefreshing];
        
        return;
    }
    
    status = 1;
    
    if (self.type == 0)
    {
        [self getNearServiceData];
        
    }else if (self.type ==1)
    {
        NSString * string = [AppCenter string:textField.text];
        
        if ([string isEqualToString:@""] || !string) {
            return;
        }
        
        [self hiddenLoadingView];
        
        [self getSeverData:string];
    }
}


- (void)willStartLocatingUser
{
    [HUD showUIBlockingIndicatorWithText:@"正在定位"];
}

- (void)didFailToLocateUserWithError:(NSError *)error
{
    [HUD showUIBlockingIndicatorWithText:@"定位失败" withTimeout:2];
}


- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //NSLog(@"heading is %@",userLocation.heading);
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
 
    self.latitude  = userLocation.location.coordinate.latitude;
    self.longitude = userLocation.location.coordinate.longitude;
    
    [HUD hideUIBlockingIndicator];
    [self getNearServiceData];
  
}



- (void)viewWillAppear:(BOOL)animated {
    
    
   [super viewWillAppear:animated];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    
   [super viewWillDisappear:animated];
    [_locService stopUserLocationService];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:textField];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:NO];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
  
}



@end
